package com.lkd.handler;

import com.lkd.business.MsgHandler;
import com.lkd.common.VMSystem;
import com.lkd.config.TopicConfig;
import com.lkd.contract.StatusInfo;
import com.lkd.contract.VmStatusContract;
import com.lkd.emq.Topic;
import com.lkd.feign.VMService;
import com.lkd.http.vo.TaskViewModel;
import com.lkd.service.TaskService;
import com.lkd.utils.JsonUtil;
import com.lkd.vo.VmVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.util.List;

/**
 * @author brianxia
 * @version 1.0
 * @date 2023-02-10 16:19
 */
@Component
@Topic(TopicConfig.VMS_STATUS_TOPIC)
@Slf4j
public class VmStatusHandler implements MsgHandler {

    @Autowired
    private TaskService taskService;
    @Autowired
    private VMService vmService;

    @Override
    public void process(String jsonMsg) throws IOException {
        //1.消息转换成对象
        if(StringUtils.isBlank(jsonMsg)){
            log.error("消息为空" + TopicConfig.VMS_STATUS_TOPIC);
            return;
        }

        //2.实体类转换json
        VmStatusContract vmStatusContract = JsonUtil.getByJson(jsonMsg, VmStatusContract.class);
        String innerCode = vmStatusContract.getInnerCode();
        List<StatusInfo> statusInfo = vmStatusContract.getStatusInfo();
        if(StringUtils.isBlank(innerCode) || CollectionUtils.isEmpty(statusInfo)){
            log.error("参数错误!" + jsonMsg + " topic:" + TopicConfig.VMS_STATUS_TOPIC);
            return;
        }

        //3.创建自动维修工单
        boolean b = statusInfo.stream().anyMatch(x -> !x.isStatus());

        if(b){
            TaskViewModel taskViewModel = new TaskViewModel();
            taskViewModel.setInnerCode(innerCode);
            taskViewModel.setAssignorId(0);
            VmVO vmInfo = vmService.getVMInfo(innerCode);
            if(vmInfo == null){
                log.error("售货机编码错误" + innerCode);
                return;
            }
            Integer leastTaskUser = taskService.getLeastTaskUser(vmInfo.getRegionId(), true);
            if(leastTaskUser == null){
                log.error("redis中不存在维修人员" + vmInfo.getRegionId());
                return;
            }
            taskViewModel.setUserId(leastTaskUser);
            taskViewModel.setProductType(VMSystem.TASK_TYPE_REPAIR);
            taskViewModel.setCreateType(VMSystem.TASK_CREATETYPE_AUTO);
            taskService.create(taskViewModel);
        }
    }
}
